package com.huxiaoshou.exam.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huxiaoshou.exam.entity.Banner;
import com.huxiaoshou.exam.mapper.BannerMapper;
import com.huxiaoshou.exam.service.BannerService;
import com.huxiaoshou.exam.service.FileUploadService;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 轮播图服务实现类
 */
@Service
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {

    private static final long FILE_SIZE = 5 * 1024 * 1024;

    @Autowired
    private FileUploadService fileUploadService;

    @Override
    public String uploadImage(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // 文件非空校验
        if (file.isEmpty()) {
            throw new RuntimeException("请选择要上传的文件！");
        }

        // 格式校验需要是image
        String contentType = file.getContentType();
        if (ObjectUtils.isEmpty(contentType) || !contentType.startsWith("image")) {
            throw new RuntimeException("轮播图只能上传图片文件！");
        }

        // 文件大小限制
        if (file.getSize() > FILE_SIZE) {
            throw new RuntimeException("图片文件大小不能超过5MB");
        }

        return fileUploadService.uploadFile(file, "banners");
    }

    @Override
    public void addBanner(Banner banner) {
        // 判断下启动状态
        if (banner.getIsActive() == null) {
            banner.setIsActive(true);
        }

        // 判断优先级
        if (banner.getSortOrder() == null) {
            banner.setSortOrder(0);
        }

        boolean isSuccess = save(banner);
        if (!isSuccess) {
            throw new RuntimeException("轮播图保存失败！");
        }
    }

    @Override
    public void updateBanner(Banner banner) {
        boolean success = this.updateById(banner);
        if (!success) {
            throw new RuntimeException("轮播图更新失败");
        }
    }

}